/**
 * 
 */
package com.maywide.jdp.system.aspect;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.jboss.cache.Cache;
import org.jboss.cache.Node;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.maywide.jdp.system.bean.OrganizationBean;
import com.maywide.jdp.system.entities.Organization;

/**
 * @author luoyang
 */
@Aspect
@Component("organizationAspect")
public class OrganizationAspect {
	private Cache<String, Object> cache = null;
	
	private OrganizationBean organizationBean = null;

	@Resource(name = "cache")
	public void setCache(Cache<String, Object> cache) {
		this.cache = cache;
	}

	@Resource(name = "organizationBean")
	public void setOrganizationBean(OrganizationBean organizationBean) {
		this.organizationBean = organizationBean;
	}

	@SuppressWarnings("unused")
	@Order(100)
	@AfterReturning(pointcut="execution(public * com.maywide.jdp.system.service.OrganizationService.update*(..)) and args(organization,..)",returning="retVal",argNames="retVal,organization")
	private void doUpdate(JoinPoint jp,Object retVal,Organization organization) throws Exception {
		String newCode = organization.getCode();
		String oldCode = ((Organization)retVal).getCode();
		if(!newCode.equals(oldCode)) {
			String newPath = new StringBuffer(Organization.ROOT_CODE_TEXT).append(organization.getCodePath()).toString();
			String oldPath = new StringBuffer(Organization.ROOT_CODE_TEXT).append(((Organization)retVal).getCodePath()).toString();
			Node<String, Object> oldNode = cache.getNode(oldPath);
			Map<String, Object> data = oldNode.getData();
			Set<Node<String, Object>> children = oldNode.getChildren();
			
			cache.put(newPath, data);
			if(children != null) {
				for(Node<String,Object> child : children) {
					cache.move(child.getFqn(), cache.getNode(newPath).getFqn());
				}
			}
		}
	}

	@SuppressWarnings("unused")
	@Order(100)
	@AfterReturning(pointcut="execution(public * com.maywide.jdp.system.service.OrganizationService.move(..)) and args(ids,parentID,..)",argNames="ids,parentID")
	private void doMove(JoinPoint jp, List<String> ids, String parentID) throws Exception {
		Organization parent = (Organization) organizationBean.load(parentID);
		for(String id : ids) {
			Organization organization = (Organization) organizationBean.load(id);
			String code = organization.getCode();
			String oldPath = new StringBuffer(Organization.ROOT_CODE_TEXT).append(organization.getCodePath()).toString();
			String newPath = new StringBuffer(Organization.ROOT_CODE_TEXT).append(parent.getCodePath()).toString();
			cache.move(oldPath, newPath);
		}
	}
}
